import React from 'react';
import util from '@/utils';
import AMapLoader from '@amap/amap-jsapi-loader';
import {
   CloseOutlined,
   HomeFilled,
   InfoCircleOutlined,
   PauseCircleOutlined,
   PlayCircleOutlined
} from '@ant-design/icons';
import {Col, Drawer, List, Modal, Popover, Row, Space, Spin} from 'antd';
import {useHistory} from 'react-router-dom';
import styles from './index.less';

const queryAllPoints = async () => {
   const {data} = await util.request({
      url: '/scenic'
   });
   return data;
};

const queryByPointId = async (id: number) => {
   const wxOpenId = localStorage.getItem('wxOpenId');
   const {data} = await util.request({
      url: `/scenic/${id}`,
      params: {
         wxOpenId
      }
   });
   return data;
};

const registerMap = async (mapContainer: any) => {

   const AMap = await AMapLoader.load({
      key: '1dc3efb3ad13e905f009b865e8a82768',
      version: '2.0',
      plugins: [],
      AMapUI: {
         version: '1.1',
         plugins: ['overlay/SimpleMarker', 'control/BasicControl', 'overlay/SimpleInfoWindow']
      }
   });

   const map = new AMap.Map(mapContainer, {
      center: [1024 / 200, 1024 * ParkMapImageRatio / 200],
      lang: 'zh_cn',
      zooms: [8, 10],
      features: [],
      zoom: 8.5,
      doubleClickZoom: false,
      layers: [
         new AMap.ImageLayer({
            bounds: new AMap.Bounds([0, 0], [1024 / 100, 1024 * ParkMapImageRatio / 100]),
            url: `${util.ossUrl}/map/park-map.png`
         })
      ],
      limitBounds: new AMap.Bounds([-1, -1], [1024 / 100 + 1, 1024 * ParkMapImageRatio / 100 + 1])
   });
   const {AMapUI}: any = window;
   map.addControl(new AMapUI.BasicControl.Zoom({
      position: 'rb',
      showZoomNum: false,
      theme: 'dark'
   }));
   map.on('click', (e: any) => {
      console.log(e);
      map.clearInfoWindow();
   });
   return map;
};

const ParkMapImageRatio = 0.47071;


const saveCustomer = async (wxOpenId: string) => {
   const {data} = await util.request({
      url: `/customer`,
      method: 'POST',
      data: {
         wxOpenId
      }
   });
   return data;
};

export default function Main() {
   const mapContainerRef = React.useRef<any>();
   const mapPointState = React.useState<Array<any>>([]);
   const selectPointState = React.useState<number>(-1);
   const menuOpenedState = React.useState<boolean>(true);
   const parkPointInfoRef = React.useRef<any>();
   const audioControlRef = React.useRef<any>();
   const modalState = React.useState<boolean>(false);
   const loadingState = React.useState<boolean>(true);
   const totalCustomerState = React.useState<number>(0);

   const history = useHistory();

   React.useEffect(() => {
      if (modalState[0]) {
         const point = mapPointState[0][selectPointState[0]];
         if (!point.content) {
            queryByPointId(point.id).then(current => {
               mapPointState[1](prevState => {
                  prevState[selectPointState[0]] = current;
                  return [...prevState];
               });
            });
         }
      }
   }, [modalState]);

   React.useEffect(() => {
      registerMap(mapContainerRef.current).then(async map => {
         map.on('click', () => {
            menuOpenedState[1](false);
         });
         const {AMapUI, AMap}: any = window;
         const points = await queryAllPoints();
         mapPointState[1](points);
         points.forEach((mark: { lng: any; lat: any; name: any; }, index: any) => {
            const marker = new AMapUI.SimpleMarker({
               topWhenClick: true,
               iconTheme: 'numv1',
               map: map,
               iconStyle: 'red',
               anchor: 'top-left',
               position: [mark.lng, mark.lat],
               label: {
                  content: `<div>${mark.name}</div>`,
                  direction: 'bottom'
               }
            });
            marker.on('click', (e: any) => {
               selectPointState[1](index);
               e.target.dom.classList.add(styles.parkMapMarkerAnimation);
               audioControlRef.current.play();
               const infoWindow = new AMap.InfoWindow({
                  anchor: 'bottom-center',
                  content: parkPointInfoRef.current
               });
               infoWindow.open(map, [e.lnglat.lng, e.lnglat.lat]);
               setTimeout(() => {
                  e.target.dom.classList.remove(styles.parkMapMarkerAnimation);
               }, 1200);
            });
         });
         loadingState[1](false);
      });
      util.request({
         url: '/customer/total'
      }).then(res => {
         totalCustomerState[1](res.data.inNum);
      });
   }, []);

   React.useEffect(() => {
      const wxOpenId = localStorage.getItem('wxOpenId');
      if (!wxOpenId) {
         const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
         });
         saveCustomer(uuid).then(res => {
            localStorage.setItem('wxOpenId', uuid);
         });
      }
   }, []);
   return <div className={styles.layout}>
      <Spin size='large' spinning={loadingState[0]} className={styles.spin} />
      <div className={styles.homeIcon} onClick={() => {
         menuOpenedState[1](true);
      }}>
         <HomeFilled />
      </div>

      <div ref={mapContainerRef} className={styles.mapContainer} />

      <Drawer
         className={styles.drawer}
         title={false}
         placement='top'
         height={400}
         closable={false}
         bodyStyle={{padding: '0'}}
         maskClosable
         onClose={(e) => {
            menuOpenedState[1](false);
         }}
         visible={menuOpenedState[0]}
      >
         <div className={styles.carousel}>
            <img src={`${util.ossUrl}/map/swiper-1.png`} />
         </div>
         <h3>静安雕塑公园欢迎您</h3>
         <div className={styles.menu}>
            <Row align='middle' justify='space-around'>
               <Col span={4} onClick={() => {
                  history.push({
                     pathname: '/article-list/1'
                  });
               }}>
                  <Space direction='vertical' align='center'>
                     <img src={`${util.ossUrl}/icon/dongtai.png`} alt='' />
                     游园攻略
                  </Space>
               </Col>
               <Col span={4} onClick={() => {
                  menuOpenedState[1](false);
               }}>
                  <Space direction='vertical' align='center'>
                     <img src={`${util.ossUrl}/icon/huodongzoo.png`} alt='' />
                     公园导览
                  </Space>
               </Col>
               <Col span={4} onClick={() => {
                  history.push({
                     pathname: '/article-list/3'
                  });
               }}>
                  <Space direction='vertical' align='center'>
                     <img src={`${util.ossUrl}/icon/kepu.png`} alt='' />
                     在线互动
                  </Space>
               </Col>
            </Row>
            <Row align='middle' justify='space-around'>
               <Col span={4}>
                  <Space direction='vertical' align='center' style={{fontSize: '12px'}}>
                     <span>
                        当日客流
                     </span>
                     <span>
                        {totalCustomerState[0]}
                     </span>
                  </Space>
               </Col>
               <Col span={4} onClick={() => {
                  history.push({
                     pathname: '/article-list/5'
                  });
               }}>
                  <Space direction='vertical' align='center'>
                     <img src={`${util.ossUrl}/icon/aidou.png`} alt='' />
                     我的爱豆
                  </Space>
               </Col>
               <Col span={4} onClick={() => {
                  history.push({
                     pathname: '/article-list/6'
                  });
               }}>
                  <Space direction='vertical' align='center'>
                     <img src={`${util.ossUrl}/icon/changguan.png`} alt='' />
                     知识讲堂
                  </Space>
               </Col>
            </Row>
         </div>
      </Drawer>
      {/*音频讲解*/}
      <div className={styles.audioControl}>
         <PlayCircleOutlined onClick={() => {
            audioControlRef.current.play();
         }} />
         <PauseCircleOutlined onClick={() => {
            audioControlRef.current.pause();
         }} />
         <Popover
            content={
               <List style={{maxHeight: '300px', overflow: 'auto', width: '150px'}}>
                  {
                     mapPointState[0].map((res: Scenic) => {
                        return <List.Item key={res.id}>
                           <img style={{width: '20px', height: '20px', marginRight: '5px'}}
                                src={res.img}
                                alt='' />
                           {res?.name}
                        </List.Item>;
                     })
                  }
               </List>
            }
            trigger={['hover', 'focus', 'click']}>
            <h5>{mapPointState[0][selectPointState[0]]?.name} <InfoCircleOutlined
               style={{fontSize: '12px'}} /></h5>
         </Popover>
         <audio ref={audioControlRef} autoPlay
                src={mapPointState[0][selectPointState[0]]?.audioPath} />
      </div>


      <Modal title={false} visible={modalState[0]}
             maskClosable
             width='85%'
             destroyOnClose
             style={{top: '35px'}}
             closeIcon={<CloseOutlined onClick={() => {
                modalState[1](false);
             }} />}
             footer={false}>
         <div className={styles.pointInfoModal}>
            <audio controls src={mapPointState[0][selectPointState[0]]?.videoPath} onPlay={() => {
               audioControlRef.current.pause();
            }} />
            <h3>{mapPointState[0][selectPointState[0]]?.name}</h3>
            <div
               dangerouslySetInnerHTML={{__html: mapPointState[0][selectPointState[0]]?.content}} />
         </div>

      </Modal>

      <template>
         <div ref={parkPointInfoRef} className={styles.parkPointInfoWindow}>
            <img src={mapPointState[0][selectPointState[0]]?.img} alt='' />
            <div>{mapPointState[0][selectPointState[0]]?.name}</div>
            <div className={styles.infoWindow}>
               <button className={styles.foot} onClick={() => {
                  modalState[1](true);
               }}>
                  介绍
               </button>
            </div>
         </div>
      </template>
   </div>;
}
